package org.csu.mypetstoreapi.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstoreapi.config.CorsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@RestController
@CrossOrigin
public class EmailController {

@Autowired
private JavaMailSender javaMailSender;

    @PostMapping ("/send/{email}")
    public ResponseEntity<String> sendEmail(HttpServletRequest request, @PathVariable("email") String email) {
        // 生成验证码


        Random random = new Random();
        StringBuilder code1 = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code1.append(random.nextInt(10));
        }
        String code=code1.toString();
        // 将验证码存储到会话中
        HttpSession session = request.getSession();
        session.setAttribute("email_code", code);
        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1928984308@qq.com");
        message.setTo(email);
        message.setSubject("登录验证码");
        message.setText("您的验证码是：" + code);
        javaMailSender.send(message);
        System.out.println("发送至邮箱的验证码为："+code);
        System.out.println(session.getId());
        return ResponseEntity.ok("验证码已发送至邮箱，请注意查收");
    }


}
